package utils;

/**
 * @Author Su
 * @Date 2025/4/30 10:03
 * @Version 1.0 （版本号）
 */
// EmailUtil.java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailUtil {
    // 邮件服务器配置
    private static final String SMTP_HOST = "smtp.qq.com";  // QQ邮箱SMTP服务器地址
    private static final String SMTP_PORT = "465";         // SSL加密端口
    private static final String USERNAME = "csl13531199422@qq.com";     // 例如：123456789@qq.com
    private static final String PASSWORD = "qzuffeoxipudgjic";      // 不是QQ密码，是SMTP授权码
    private static final String FROM_EMAIL = "csl13531199422@qq.com";   // 与USERNAME相同
    private static final String FROM_NAME = "云文档平台验证码";     // 发件人显示名称

    public static boolean sendVerificationCode(String toEmail, String code) {
        // 配置邮件服务器
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.enable", true);

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        try {
            // 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL, FROM_NAME));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject("云文档平台 - 邮箱验证码");

            // 邮件内容
            String content = String.format(
                    "您的验证码是: <strong>%s</strong><br><br>" +
                            "验证码将在1分钟后失效，请尽快使用。<br>" +
                            "如果不是您本人操作，请忽略此邮件。", code);

            message.setContent(content, "text/html;charset=UTF-8");

            // 发送邮件
            new Thread(() -> {
                try {
                    Transport.send(message);
                }catch (MessagingException ignored) {}
                }).start();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}